import logging

from django.contrib.gis.gdal.prototypes.geom import is_empty
from django.shortcuts import render
from .models import User
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from django.http import JsonResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.core.signing import Signer
from django.core.cache import cache
from datetime import timedelta
from django.shortcuts import render
import random
import string
import string,random
from django.core.cache import cache
from django.core.signing import Signer
# Create your views here.

# 注册
@api_view(['POST'])
def zhuce(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    gender=data.get('gender')
    age=data.get('age')

    User(name=name,gender=gender,age=age).save()
    return JsonResponse({
        'code':200,
        'msg':'注册成功'
    })

# 返回所有用户信息
@api_view(['GET'])
def selectall(request):

    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'code':404,
            'msg':'未登录，请先登录'
        })
    # vue中
    page=request.GET.get('page')
    pageSize=request.GET.get('pageSize')
    logging.info(f'查看从vue中得到的数据:{page,pageSize}')
    userobj=User.objects.all().values()
    # 分页
    pageobjs=Paginator(userobj,pageSize)
    try:
        singlepageobj=pageobjs.page(page)
    except EmptyPage:
        singlepageobj=pageobjs.page(pageobjs.num_pages)
    except PageNotAnInteger:
        singlepageobj=pageobjs.page(1)

    lis=[]
    for item in singlepageobj.object_list:
        lis.append({
            # 一定要返回id
            'id':item.get('id'),
            'name':item.get('name'),
            'gender':item.get('gender'),
            'age':item.get('age'),
            'createtime':item.get('createtime'),
            'updatetime':item.get('updatetime')
        })
    return JsonResponse({
        'code':200,
        # 根据vue中的data
        'data':lis,
        'items':userobj.count()
    })

#删除
@api_view(['DELETE'])
def deleteitem(request,itemid):
    obj=User.objects.get(id=itemid)
    obj.delete()
    return JsonResponse({
        'code':200,
        'msg':'删除成功'
    })

#入库
@api_view(['GET'])
def getuserinfo(request,itemid):
    flag, name = checktoken(request)
    if flag is False:
        return JsonResponse({
            'code': 404,
            'msg': '未登录，请先登录'
        })

    obj=User.objects.get(id=itemid)
    return JsonResponse({
        'code':200,
        'name':obj.name,
        'age':obj.age,
        'gender':obj.gender,
        'createtime':obj.createtime,
        'updatetime':obj.updatetime
    })
#修改
@api_view(['PUT'])
def updateitem(request,itemid):
    obj=User.objects.get(id=itemid)
    data=JSONParser().parse(request)

    name=data.get('name')
    age=data.get('age')
    gender=data.get('gender')

    obj.name=name
    obj.gender=gender
    obj.age=age

    obj.save()
    return JsonResponse({
        'code':200,
        'msg':'修改成功'
    })

# 登录
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)
    # username根据vue
    name=data.get('username')
    password=data.get('password')
    if User.objects.filter(name=name).exists() is False:
        return JsonResponse({
            'code':200,
            'msg':'用户不存在'
        })
    obj=User.objects.get(name=name)
    if str(obj.age)!= password:
        return JsonResponse({
            'code':202,
            'msg':'密码不正确'
        })
    # 产生token
    token=createtoken(name)
    return JsonResponse({
        'code':200,
        'msg':'登录成功',
        'token':token
    })

# 搜索
@api_view(['GET'])
def getconditionitem(request):
    name=request.GET.get('name')
    gender=request.GET.get('gender')
    age=request.GET.get('age')

    logging.info(f'从vue端传过来的name:{name}')
    logging.info(f'从vue端传过来的gender:{gender}')
    logging.info(f'从vue端传过来的age:{age}')

    if is_empty(name) and is_empty(gender) and is_empty(age):
        return JsonResponse({
            'code':404,
            'msg':'请输入查询条件'
        })
    if is_empty(name) is False and is_empty(gender) is False and is_empty(age) is False:
        allobjs=User.objects.filter(name=name,gender=gender,age=age)
        lis=[]
        for item in allobjs:
            lis.append({
                # 一定要返回id
                'id': item.id,
                'name': item.name,
                'gender': item.gender,
                'age': item.age,
                'createtime': item.createtime,
                'updatetime': item.updatetime
            })
        return JsonResponse({
            'code': 200,
            # 根据vue中的data
            'data': lis,
            'items': allobjs.count()
        })

    if is_empty(name) is False and is_empty(gender) is True and is_empty(age) is True:
        allobjs=User.objects.filter(name=name)
        lis=[]
        for item in allobjs:
            lis.append({
                # 一定要返回id
                'id': item.id,
                'name': item.name,
                'gender': item.gender,
                'age': item.age,
                'createtime': item.createtime,
                'updatetime': item.updatetime
            })
        return JsonResponse({
            'code': 200,
            # 根据vue中的data
            'data': lis,
            'items': allobjs.count()
        })
    if is_empty(name) is True and is_empty(gender) is False and is_empty(age) is False:
        allobjs = User.objects.filter(age=age,name=name)
        return selectcondition(allobjs)

    if is_empty(name) is True and is_empty(gender) is False and is_empty(age) is True:
        allobjs = User.objects.filter(gender=gender)
        return selectcondition(allobjs)

    if is_empty(name) is False and is_empty(gender) is False and is_empty(age) is True:
        allobjs = User.objects.filter(name=name,gender=gender)
        return selectcondition(allobjs)

    if is_empty(name) is False and is_empty(gender) is True and is_empty(age) is False:
        allobjs=User.objects.filter(name=name,age=age)
        return selectcondition(allobjs)

    if is_empty(name) is True and is_empty(gender) is True and is_empty(age) is False:
        allobjs=User.objects.filter(age=age)
        return selectcondition(allobjs)


# 产生token
def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token
# 校验token
def checktoken(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'XXXX'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    checktoken=cache.get(f'test_{name}')
    if checktoken is None:
        return False,'XXXX'
    return True,name
# 判空
def is_empty(c):
    return c is None or str(c).strip()==''

def selectcondition(allobjs):
    lis = []
    for item in allobjs:
        lis.append({
            # 一定要返回id
            'id': item.id,
            'name': item.name,
            'gender': item.gender,
            'age': item.age,
            'createtime': item.createtime,
            'updatetime': item.updatetime
        })
    return JsonResponse({
        'code': 200,
        # 根据vue中的data
        'data': lis,
        'items': allobjs.count()
    })

# # 分组查询
# @api_view(['GET'])
# def getgroupbyinfo(request):
#     datas=User.objects.values('publisher').annotate(maxprice=M)
@api_view(['GET'])
def getgenderlist(request):
    gendervalues=User.objects.values('gender').annotate()
    logging.info(f'查看以性别字段分组后的内容:{gendervalues}')
    lis=[]
    for item in gendervalues:
        lis.append({
            'id':item.get('gender'),
            'name':item.get('gender'),
        })
